package com.maike.babyname.subscribers;

import android.content.Context;

import com.maike.babyname.network.HttpResult;

import com.google.gson.Gson;
import com.maike.babyname.progress.ProgressCancelListener;
import com.maike.babyname.progress.ProgressDialogHandler;
import com.maike.babyname.utils.LogUtils;
import com.maike.babyname.utils.NetworkUtil;
import com.maike.babyname.utils.ToastUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 用于在Http请求开始时，自动显示一个ProgressDialog
 * 在Http请求结束是，关闭ProgressDialog
 * 调用者自己对请求数据进行处理
 */
public class ProgressSubscriber<T extends HttpResult> extends Subscriber<T> implements ProgressCancelListener {

    private SubscriberListener mSubscriberOnNextListener;
    private ProgressDialogHandler mProgressDialogHandler;

    private Gson mGson = new Gson();
    private Context mContext;

    public ProgressSubscriber(AbstractSubscriberListener mSubscriberOnNextListener, Context context) {
        this.mSubscriberOnNextListener = mSubscriberOnNextListener;
        this.mContext = context;
        mProgressDialogHandler = new ProgressDialogHandler(context, this, true);
    }

    public ProgressSubscriber(AbstractSubscriberListener mSubscriberOnNextListener, Context context, boolean ishow) {
        this.mSubscriberOnNextListener = mSubscriberOnNextListener;
        this.mContext = context;
        if (ishow)
            mProgressDialogHandler = new ProgressDialogHandler(context, this, true);
    }

    private void showProgressDialog() {
        LogUtils.e("-------------展示弹窗");
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        LogUtils.e("-------------销毁1");
        if (mProgressDialogHandler != null) {
            LogUtils.e("-------------销毁2");
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mProgressDialogHandler.dismissProgressDialog();
            mProgressDialogHandler = null;
        }
    }

    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {
        if (!NetworkUtil.isNetConnected(mContext) && !isUnsubscribed()) {
            ToastUtils.showShortToast("请检查网络连接后重试！");
            callNetworkError(new Exception("网络不可用"));
            unsubscribe();
        } else {
            showProgressDialog();
        }
    }

    /**
     * 完成，隐藏ProgressDialog
     */
    @Override
    public void onCompleted() {

    }

    /**
     * 对错误进行统一处理
     * 隐藏ProgressDialog
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {

        LogUtils.e(e);
        if (mSubscriberOnNextListener != null) {
            mSubscriberOnNextListener.onError(e);
        }
        dismissProgressDialog();
        if (e instanceof SocketTimeoutException) {
            ToastUtils.showShortToast("网络中断，请检查您的网络状态");
            callNetworkError(e);
        } else if (e instanceof ConnectException) {
            ToastUtils.showShortToast("网络中断，请检查您的网络状态");
            callNetworkError(e);
        } else if (e instanceof UnknownHostException) {
            ToastUtils.showShortToast("网络中断，请检查您的网络状态");
            callNetworkError(e);
        } else if (e instanceof HttpException) {
            ToastUtils.showShortToast("网络中断，请检查服务器及您的网络是否正常");
            callNetworkError(e);
        } else {
            ToastUtils.showShortToast("error:" + e.getMessage());
            throw new RuntimeException(e);
        }

    }

    void callNetworkError(Throwable e) {
        if (mSubscriberOnNextListener != null) {
            mSubscriberOnNextListener.onNetworkError(e);
        }
    }

    /**
     * 将onNext方法中的返回结果交给Activity或Fragment自己处理
     *
     * @param result 创建Subscriber时的泛型类型
     */
    @Override
    public void onNext(T result) {
        dismissProgressDialog();
        if (result != null) {
            if (result.getStatus() == 200) {
                if (mSubscriberOnNextListener != null) {
                    mSubscriberOnNextListener.onNext(result);
                }
            } else if (result.getStatus() == 1000) {

                callNetworkError(new Throwable());
            } else {
                if (mSubscriberOnNextListener != null) {

                    mSubscriberOnNextListener.onError(new Exception(result.getMessage()));

                }
            }
        } else {
            ToastUtils.showShortToast("服务器错误");
        }
    }


    /**
     * 取消ProgressDialog的时候，取消对observable的订阅，同时也取消了http请求
     */
    @Override
    public void onCancelProgress() {
        if (mSubscriberOnNextListener != null) {
            mSubscriberOnNextListener.onCancel();
        }
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }


}